package com.zecan.blog.security.handler;

import cn.hutool.json.JSONUtil;
import com.zecan.blog.common.status.UserStatus;
import com.zecan.blog.utils.BlogResultUtils;
import com.zecan.blog.utils.JWTUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName LogoutSuccessHandler
 * @Description
 * @date 2022/10/31 9:47
 * @Version 1.0
 * 用户登出处理器
 */
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private JWTUtils jwtUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        // 登出之后 设置jwt的值为 ""
        response.setHeader(jwtUtils.getHeader(),"");


        // 设置响应 为 退出登录成功
        outputStream.write(JSONUtil.toJsonStr(BlogResultUtils.userStatus(UserStatus.USER_LOGOUT_SUCCESS)).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }


}
